package com.baijiaoxi.utils.sms.aliyun;

import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.baijiaoxi.common.model.base.CommonResponse;
import com.baijiaoxi.utils.sms.aliyun.model.MultiSendSmsRequest;

/**
 * Created by shixj on 2018/6/8.
 */
public class AliyunSmsHelper {
    public static CommonResponse<SendSmsResponse> send(MultiSendSmsRequest request, IAcsClient acsClient) throws ClientException {
        CommonResponse commonResponse = new CommonResponse();
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request.getSendSmsRequestCN());
        if (sendSmsResponse.getCode().equalsIgnoreCase("OK"))
            commonResponse.setStatus("200");
        else sendSmsResponse = acsClient.getAcsResponse(request.getSendSmsRequestOther());
        if (sendSmsResponse.getCode().equalsIgnoreCase("OK"))
            commonResponse.setStatus("200");
        else commonResponse.setStatus("400");
        commonResponse.setMsg(sendSmsResponse.getMessage());
        commonResponse.setData(sendSmsResponse);
        return commonResponse;
    }

    public static CommonResponse<SendSmsResponse> send(SendSmsRequest request, IAcsClient acsClient) throws ClientException {
        CommonResponse commonResponse = new CommonResponse();
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        if (sendSmsResponse.getCode().equalsIgnoreCase("OK"))
            commonResponse.setStatus("200");
        else commonResponse.setStatus("400");
        commonResponse.setMsg(sendSmsResponse.getMessage());
        commonResponse.setData(sendSmsResponse);
        return commonResponse;
    }

    /**
     * 新建短信对象
     *
     * @param phone
     * @param templateCode
     * @param params
     * @return
     */
    public static SendSmsRequest buildSendSmsRequest(String signName,String phone, String templateCode, String... params) {

        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(phone);
        sendSmsRequest.setSignName(signName);
        sendSmsRequest.setTemplateCode(templateCode);
        if (params != null && params.length > 0) {
            String templateParam = "{";
            for (int i = 0; i < params.length; i++) {
                String param = params[i] == null ? "" : params[i];
                if (i % 2 == 1) {
                    templateParam += "\"" + param + "\"";
                    if (i != params.length - 1)
                        templateParam += ",";
                } else templateParam += "\"" + param + "\":";
            }
            templateParam += "}";
            sendSmsRequest.setTemplateParam(templateParam);
        }
        return sendSmsRequest;

    }
}
